const app = getApp()
const http = require('../../../utils/util')
const Base64 = require('../../../utils/base')
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    methodsTxt:'',
    isShowPayClass:false,//false 普通弹窗 true带二维码
    payClass: 'none', //支付成功弹出层显示与隐藏 普通
    payTwoClass:'none',//支付成功弹出层显示与隐藏 带二维码
    payThreeClass:"none",//支付前弹出层显示与隐藏
		orderDetail: {}, //订单详细信息
		pay_type: 1, //支付类型 1微信支付 2储蓄卡支付
		otherDate: {},
		couponClass: 'none', //优惠券显示隐藏
		couponList: [], //优惠券数据  type值为1-5时 美团优惠券 7次卡 8期卡 9小时卡
		couponIndex: -1, //选中的优惠券索引
		currentCoupon: '', //选中的优惠券
		isPaying: true, //是否正在支付
		finalPrice: null, //最终价格（使用优惠券后的价格）
		prefPrice: 0, //优惠价格
		order_id:null, //订单id用于跳转至订单详情页面
		// second:5, //倒计时跳转订单详情
		//interval:false, //
		conduct:'', //自习室守则
    phoneClass:'none', //授权手机显示隐藏
    note:'',//温馨提示
    codeImg:'',//二维码
	},
	// 自习室守则
	toshowze(){
		this.setData({
			interval:true
		})
		wx.navigateTo({
			url:'/pages/rules/rules?conduct='+JSON.stringify(this.data.conduct)
		})
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		let _this=this
		if(this.data.payClass=='show'){
			this.setData({
				interval:false,
				// second:5
			},()=>{
				// let interval= setInterval(()=>{
				// 	if(_this.data.interval){
				// 		clearInterval(interval)
				// 	}
				// 	if(_this.data.second==1){
				// 		clearInterval(interval)
				// 		_this.payhide()
				// 	}
				// 	_this.setData({
				// 		second: --_this.data.second
				// 	})
				// },1000)
      })
    }
    console.log("进来了=====")
    this.bulletFrame()    
  },
  bulletFrame(){
  // 准备参数
  let data = {
    user_id: wx.getStorageSync('user_id'),
    user_token: wx.getStorageSync('user_token'),
    store_id: this.data.orderDetail.store_id,
  }
    //查询是否当前店显示二维码
    http.post('store/bullet_frame', Base64.encode(JSON.stringify(data))).then((res) => {
        console.log("res====",res)
        if(res.status==1){
            this.setData({
              isShowPayClass:res.result.isShowQrCode,
              note:res.result.note,
              codeImg:res.result.img
            })
        }
    })
    },
	// 隐藏手机号弹出层
	hidePhone(){
		this.setData({
			phoneClass:'none'
		})
	},
	//获取手机号
	getPhoneNumber(e){
		  this.setData({
			  phoneClass:'none'
		  })
		  if(e.detail.errMsg=='getPhoneNumber:ok'){
		  	wx.login({
				success:(res)=>{
					let data={
						encryptedData:e.detail.encryptedData,
						code:res.code,
						iv:e.detail.iv,
						user_id:wx.getStorageSync('user_id'),
						user_token:wx.getStorageSync('user_token'),
					}
					http.post('user/postPhone',Base64.encode(JSON.stringify(data))).then(res=>{
						if(res.status==1){
							wx.setStorageSync('phone',res.result)
							wx.showToast({
								title:'授权成功',
								icon:'none'
							})
						}else{
							wx.showToast({
								title:res.msg,
								icon:'none'
							})
						}
					})
				}
			})
		  }else{
		  	wx.showToast({
		  		title:'授权失败',
		  		icon:'none'
		  	})
		  }
  },
  payBefore(e){
    this.setData({
      payThreeClass: "show",
      methodsTxt:e.currentTarget.dataset.pay
    })
  },
  
	// 支付
	async payMethods() {
    this.setData({
      payThreeClass: "none",
    })
		let _this = this
		//判断用户是否授权手机号
		let phone= wx.getStorageSync('phone')
		if(!phone){
		   return this.setData({
				phoneClass:'show'
			})
		}
		
    if (!this.data.isPaying) return
		this.setData({
			isPaying: false
		})
		//支付方式
		let methods =this.data.methodsTxt
		let pay_type = methods == 'wx' ? 1 : 2
		if (this.data.finalPrice == 0 && pay_type == 1) { //0元时调用储蓄卡支付
			pay_type = 2
		}

		// 准备参数
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			store_id: this.data.orderDetail.store_id,
			start_time: this.data.orderDetail.date + ' ' + this.data.orderDetail.start_hours + ':00',
			end_time: this.data.orderDetail.date + ' ' + this.data.orderDetail.end_hours + ':00',
			seat_id: this.data.orderDetail.seat_num,
			genre_id: this.data.orderDetail.genre_id,
			pay_type: pay_type,
			price: this.data.finalPrice,
			coupon_type: this.data.currentCoupon ? this.data.currentCoupon.type : 0,
			coupon_id: this.data.currentCoupon ? this.data.currentCoupon.id : 0
    }
		//支付逻辑
		http.post('store/seatOrder', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				if (pay_type == 1) { //微信支付
					let data = res.result
					wx.requestPayment({
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						success: (res) => {
              if(_this.data.isShowPayClass){
                _this.setData({
                  payTwoClass:'show',
                  order_id:data.order_id,
                  conduct:data.conduct
                 })
              }else{
                _this.setData({
                  payClass:'show',
                  order_id:data.order_id,
                  conduct:data.conduct
                 })
              }
						},
						fail: () => {
							wx.showToast({
								title: '支付失败',
								icon: 'none'
							})
						},
						complete: () => {
							_this.setData({
								isPaying: true
							})
						}
					})
				} else { //储蓄卡支付
          if(_this.data.isShowPayClass){
            _this.setData({
              payTwoClass:'show',
              order_id: res.result.order_id,
              conduct:res.result.conduct
             })
          }else{
            _this.setData({
              payClass:'show',
              order_id: res.result.order_id,
              conduct:res.result.conduct
             })
          }
				}
			} else {
				_this.setData({
					isPaying: true
				})
				wx.showToast({
					title: res.message,
					icon: 'none'
				})
				if (res.message == '储值点不足') {
					wx.showModal({
						title: '提示',
						content: '储值卡余额不足',
						success: (res) => {
							if (res.confirm) {
								wx.switchTab({
									url: '/pages/purchase/purchase?store_id=' +
										_this.data.orderDetail.store_id
								})
							}
						}
					})
				}
			}
		})
  },
  payThreeHide(){
    this.setData({
      payThreeClass:"none"
    })
  },
	// 隐藏支付成功弹出层 去往订单
	payhide() {
		// this.setData({
		// 	interval:true
		// })
		getApp().globalData.is_from = true
		let params={
			order_id:this.data.order_id,
			type:1,
			store_id:this.data.orderDetail.store_id
		}
		wx.reLaunch({
			url: '/pages/mine/record/recordorderdetails/recordorderdetails?params='+JSON.stringify(params)
		})
	},
	//去往订单
	toOrder() {
		// this.setData({
		// 	interval:true
		// })
		getApp().globalData.is_from = true
		let params={
			order_id:this.data.order_id,
			type:1,
			store_id:this.data.orderDetail.store_id
		}
		wx.reLaunch({
			url: '/pages/mine/record/recordorderdetails/recordorderdetails?params='+JSON.stringify(params)
		})
	},
	//重新选择座位
	changeSeat() {
		wx.navigateBack({
			delta: 1
		})
	},
	//显示优惠券列表
	showCoupon() {
		this.setData({
			couponClass: 'show'
		})
	},
	// 隐藏优惠券
	hideCoupon() {
		this.setData({
			couponClass: 'hide',
			// currentCoupon:'',
			// couponIndex:-1
		})
		setTimeout(() => {
			this.setData({
				couponClass: 'none'
			})
		}, 200)
	},
	//选择优惠券
	changeCoupon(e) {
		//选中的优惠券
		let current = this.data.couponList[e.currentTarget.dataset.index]
		//判断优惠券能否使用
		if (current.status !== '未使用') {
			return wx.showToast({
				title: '此优惠券不能使用'
			})
		}

		if (this.data.couponIndex == e.currentTarget.dataset.index) {
			this.setData({
				couponIndex: -1,
				currentCoupon: '',
				finalPrice: this.data.orderDetail.subtotal,
				prefPrice: 0
			})
		} else {
			this.setData({
				couponIndex: e.currentTarget.dataset.index,
				currentCoupon: current
			}, () => {
				//判断优惠券类型
				if (current.type == 7) { // 7 次卡
				    let {date,start_hours} = this.data.orderDetail
					//1.判断是否超过使用期限
					//获取当前时间戳
					let nowTime = new Date().getTime()
					//获取选择日期后的时间戳
					let d=date+' '+start_hours
					let changeTime=new Date(d).getTime()
					//优惠卡到期时间戳
					let endTime = new Date(current.end_time).getTime()
					if (nowTime >= endTime || changeTime>=endTime) {
						this.setData({
							couponIndex: -1,
							currentCoupon: ''
						})
						return wx.showToast({
							title: '预约时间超出优惠券有效期，不可使用',
							icon: 'none'
						})
					}
					//2.是否超过使用次数
					if (current.car_num == 0) { //可使用次数为0
						this.setData({
							couponIndex: -1,
							currentCoupon: ''
						})
						return wx.showToast({
							title: '不可使用，可使用次数为0',
							icon: 'none'
						})
					}
					//3.计算优惠后的价格
					let {
						hours,
						subtotal,
						predict_price
					} = this.data.orderDetail // hours用户下单使用时长 subtotal总金额（不减优惠券）predict_price单价
					let hour_num = current.hour_num //单次可使用时长
					if (hour_num >= hours) { //单次可使用时长大于等于用户选择时长，优惠后价格为0
						this.setData({
							finalPrice: 0,
							prefPrice:subtotal
						})
					} else { //单次可使用时长小于用户选择时长
						let num=this.accMul(hour_num,predict_price)
						this.setData({
							prefPrice: num,
							finalPrice: this.subtr(subtotal,num)
						})
					}
				} else if (current.type == 8) { // 8 周卡
					this.setData({
						prefPrice: this.data.orderDetail.subtotal,
						finalPrice: 0
					})
				} else if (current.type == 9) { // 9 小时卡
					let hour_num = current.hour_num // 获取小时卡剩余时长
					let {
						hours,
						subtotal,
						predict_price
					} = this.data.orderDetail // hours用户下单使用时长 subtotal总金额（不减优惠券）predict_price单价
					if (hour_num == 0) { //可使用时长为0
						this.setData({
							couponIndex: -1,
							currentCoupon: '',
							prefPrice: 0,
							finalPrice: this.data.orderDetail.subtotal
						})
					} else if (hour_num < hours) { //可使用时长小于用户选择的时长
						let num=this.accMul(hour_num,predict_price)
						this.setData({
							prefPrice: num,
							finalPrice: this.subtr(subtotal,num)
						})
					} else {
						this.setData({
							prefPrice: this.data.orderDetail.subtotal,
							finalPrice: 0
						})
					}
				} else if (current.type == 3) { // 3 美团优惠券
					let {
						hours,
						subtotal,
						predict_price,
						date,
						start_hours
					} = this.data.orderDetail // hours用户下单使用时长 subtotal总金额（不减优惠券）predict_price单价
					//1.判断是否超过使用期限
					//获取当前时间戳
					let nowTime = new Date().getTime()
					//获取选择日期后的时间戳
					let d=date+' '+start_hours
					let changeTime=new Date(d).getTime()
					//优惠卡到期时间戳
					let endTime = new Date(current.end_time).getTime()
					if (nowTime >= endTime || changeTime>=endTime) {
						this.setData({
							couponIndex: -1,
							currentCoupon: ''
						})
						return wx.showToast({
							title: '预约时间超出优惠券有效期，不可使用',
							icon: 'none',
							duration:2500
						})
					}
					//2.计算优惠后价格
					let hour_num = current.hour_num //可使用时长
					if(hour_num>=hours){
						this.setData({
							prefPrice: subtotal,
							finalPrice: 0
						})
					}else{
						let num=this.accMul(hour_num,predict_price)
						this.setData({
							prefPrice: num,
							finalPrice: this.subtr(subtotal,num)
						})
					}
				}
			})
		}
	},
	//获取优惠券信息
	getCouponList() {
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			store_id: this.data.orderDetail.store_id,
			type: 1,
			start_time: this.data.orderDetail.date + ' ' + this.data.orderDetail.start_hours,
			end_time: this.data.orderDetail.date + ' ' + this.data.orderDetail.end_hours,
			genre_id: this.data.orderDetail.genre_id,
		}
		http.post('user/coupon', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				this.setData({
					couponList: res.result
				})
			} else {
				wx.showToast({
					title: '获取优惠券失败',
					icon: 'none'
				})
			}
		})
	},
	//优惠券确定按钮
	confirmCoupon(e) {
		let current = this.data.couponList[this.data.couponIndex]
		if (!current){
			this.setData({
				couponClass: 'hide',
				currentCoupon: current
			})
			setTimeout(() => {
				this.setData({
					couponClass: 'none'
				})
			}, 200)
			return
		}
		if (current.status !== '未使用') {
			wx.showToast({
				title: '此优惠券不能使用',
				icon: 'none'
			})
			this.setData({
				currentCoupon: '',
				couponIndex: -1
			})
		} else {
			this.setData({
				couponClass: 'hide',
				currentCoupon: current
			})
			setTimeout(() => {
				this.setData({
					couponClass: 'none'
				})
			}, 200)
		}

	},
	//去储值
	tochuzhi(){
		app.globalData.isFrom2=false
		app.globalData.store_id=this.data.orderDetail.store_id
		app.globalData.type_c=4
		app.globalData.seatorderParams=this.data.orderDetail
		app.globalData.isFrom1=true
		wx.switchTab({
			url:'/pages/purchase/purchase'
		})
	},
	//解决js减法精度问题
	subtr(arg1,arg2){ 
	    var r1,r2,m,n; 
	    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
	    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
	    m=Math.pow(10,Math.max(r1,r2)); 
	    n=(r1>=r2)?r1:r2; 
	    return ((arg1*m-arg2*m)/m).toFixed(n); 
	},
	//乘法计算精度
	accMul(arg1,arg2){ 
		var m=0,s1=arg1.toString(),s2=arg2.toString(); 
		try{m+=s1.split(".")[1].length}catch(e){} 
		try{m+=s2.split(".")[1].length}catch(e){} 
		return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
	 },
	

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let params = JSON.parse(options.data)
		this.setData({
			orderDetail: params,
			otherDate: app.globalData,
			finalPrice: params.subtotal
		}, () => {
			this.getCouponList()
		})
	},

	/**ƒ√
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
